import axios from "axios";
// create an axios instance
let service = axios.create({
  timeout: 30 * 1000,
  baseURL: "https://iot.dunji.tech",
});

// request interceptor
service.interceptors.request.use(
  (config) => {
    // do something before request is sent
    if (config.method === "formdata") {
      config.headers.post["Content-Type"] = "multipart/form-data;charset=utf-8";
      config.method = "post";
      const fPar = new FormData();
      for (const key in config.params) {
        fPar.append(key, config.params[key]);
      }
      config.data = fPar;
      config.params = "";
    } else if (config.method === "query") {
      config.method = "post";
      config.data = "";
    } else if (config.method === "post") {
      config.data = config.params;
      config.params = "";
    }
    config.headers["Cache-Control"] = "no-cache";
    return config;
  },
  (error) => {
    // do something with request error
    console.log(error); // for debug
    return Promise.reject(error);
  }
);
// response interceptor 响应拦截器
service.interceptors.response.use(
  (response) => {
    // 请求为200通过
    if (response.status === 200) {
      return response.data;
    } else {
      // 否则抛出异常
      return Promise.reject(response);
    }
  },
  (error) => {
    console.log("err" + error); // for debug
    return Promise.reject(error);
  }
);

const request = (url = "", params = {}, method) => {
  return new Promise((resolve, reject) => {
    service({
      url,
      params,
      method,
    })
      .then((res) => {
        console.log("request", res);
        resolve(res);
      })
      .catch((err) => {
        reject(err);
      });
  });
};
export const post = (url = "", params = {}) => {
  return service({
    url,
    params,
    method: "post",
  });
};
export const get = (url = "", params = {}) => {
  return service({
    url,
    params,
    method: "get",
  });
};
export default request;
